import { getToken } from '../services/authService';
import { toast } from 'sonner';


const API_BASE_URL =  process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api';

interface RequestOptions extends RequestInit {
  params?: Record<string, any>;
}

export const apiRequest = async <T>(
  endpoint: string,
  options: RequestOptions = {}
): Promise<T> => {
  const { params, ...fetchOptions } = options;
  
  // console.log(`正在发送API请求到: ${endpoint}`);
  // console.log(`请求参数:`, params);
  
  // 构建URL
  let url = `${API_BASE_URL}${endpoint}`;
  if (params) {
    const queryParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        queryParams.append(key, String(value));
      }
    });
    const queryString = queryParams.toString();
    if (queryString) {
      url += `?${queryString}`;
    }
  }
  
  // console.log(`完整请求URL: ${url}`);

  // 设置默认headers
  const headers: Record<string, string> = {};
  
  // 只有当请求体不是FormData时才设置默认的Content-Type
  if (!(fetchOptions.body instanceof FormData)) {
    headers['Content-Type'] = 'application/json';
  }
  
  // 合并用户提供的headers
  Object.assign(headers, fetchOptions.headers);

  // 添加认证token
  const token = getToken();
  if (token) {
      (headers as any)['Authorization'] = `Bearer ${token}`;
  }

  try {
    // console.log(`开始发送fetch请求...`);
    const response = await fetch(url, {
      ...fetchOptions,
      headers,
    });

    // console.log(`收到响应，状态码: ${response.status}`);
          // 检查是否是401未授权错误
      if (response.status === 401) {
          // 清除用户信息和认证token
          
            localStorage.removeItem('auth_token');
            localStorage.removeItem('user');
            // 显示重新登录提示
            toast.error('登录状态已过期，请重新登录');
          
        }

    // 检查响应状态
    if (!response.ok) {
      // console.error(`API请求失败，状态码: ${response.status}`);
      const errorData = await response.json().catch(() => ({
        message: `请求失败: ${response.status} ${response.statusText}`,
      }));
      throw new Error(errorData.message || '请求失败');
    }

    // 处理空响应
    const contentType = response.headers.get('content-type');
    if (contentType && contentType.includes('application/json')) {
      // console.log(`响应是JSON格式，开始解析...`);
      const responseData = await response.json();
      // console.log(`API响应原始数据 [${endpoint}]:`, JSON.stringify(responseData, null, 2));
      
      // 检查响应数据结构
      // console.log(`响应数据字段:`, Object.keys(responseData));
      // 返回原始响应数据，保持通用性质
      return responseData;
    }
    // console.log(`响应不是JSON格式`);
    return {} as T;
  } catch (error) {
      // console.error(`API请求错误 [${endpoint}]:`, error);
      // 通用错误处理，直接抛出错误
      throw error;
  }
};

// 便捷方法
export const get = <T>(endpoint: string, params?: Record<string, any>): Promise<T> => {
  return apiRequest<T>(endpoint, { method: 'GET', params });
};

export const post = <T>(endpoint: string, data?: any): Promise<T> => {
  return apiRequest<T>(endpoint, {
    method: 'POST',
    // 对于FormData类型，直接传递，不进行JSON.stringify
    body: data instanceof FormData ? data : JSON.stringify(data),
  });
};

export const put = <T>(endpoint: string, data?: any): Promise<T> => {
  return apiRequest<T>(endpoint, {
    method: 'PUT',
    // 对于FormData类型，直接传递，不进行JSON.stringify
    body: data instanceof FormData ? data : JSON.stringify(data),
  });
};

export const patch = <T>(endpoint: string, data?: any): Promise<T> => {
  return apiRequest<T>(endpoint, {
    method: 'PATCH',
    // 对于FormData类型，直接传递，不进行JSON.stringify
    body: data instanceof FormData ? data : JSON.stringify(data),
  });
};

export const del = <T>(endpoint: string): Promise<T> => {
  return apiRequest<T>(endpoint, { method: 'DELETE' });
};
